<template>
  <div class="page-mj">
    <div class="inner custom-scroll flex-h h100">
      <div class="mj-box">
        <!-- <h2>AI绘画</h2> -->
        <div class="mj-params" :style="{ height: paramBoxHeight + 'px' }">
          <el-form :model="params" label-width="80px" label-position="left">
            <div class="param-line flex-h flex-hv-center mb-10">
              <span class="left-box-label sun-color mr-10">模型选择：</span>
              <div class="form-item-inner ai-select">
                <el-select
                  size="small"
                  v-model="params.platform"
                  placeholder="请选择模型"
                  class="role-select"
                  style="width: 150px"
                  @change="platformChange"
                >
                  <el-option
                    v-for="item in platformOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
            <div class="param-line flex-h flex-hv-center mb-10" v-if="params.platform === 'Jimeng'">
              <span class="left-box-label sun-color mr-10">模型版本：</span>
              <div class="form-item-inner ai-select">
                <el-select
                  size="small"
                  v-model="params.model"
                  placeholder="请选择模型版本"
                  popper-class="modelVersionSelect"
                  style="width: 150px"
                >
                  <el-option
                    v-for="item in modelVersionOption"
                    :key="item.model"
                    :label="item.name"
                    :value="item.model"
                    :disabled="params.image != '' && !item.i2iFlag"
                  >
                    <div class="custom-option flex-v">
                      <span class="title">{{ item.name }}</span>
                      <span class="desc ft-12">{{ item.description }}</span>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </div>
            <div class="param-line pt mb-10">
              <span class="mj-title">
                <!-- <i class="iconfont icon-chuangyi liner-text mr-5"></i> -->
                创意描述（必填）：</span
              >
            </div>
            <div class="param-line pt">
              <el-input
                :show-word-limit="true"
                v-model="params.prompt"
                maxlength="500"
                :autosize="{ minRows: 8, maxRows: 8 }"
                type="textarea"
                ref="promptRef"
                placeholder="请输入要生成的内容....."
              />
            </div>

            <div class="tag-select">
              <div class="inner">
                <span class="tag" @click="selectTag(tag)" v-for="tag in tags" :key="tag.value">{{
                  tag.label
                }}</span>
              </div>
            </div>

            <div class="pt-15 pb-15 flex-h flex-vh-center pl-10 pr-10">
              <span>
                <!-- <i class="iconfont icon-tupian liner-text mr-5"></i> -->
                参考图 / 垫图</span
              >
              <el-tooltip
                effect="light"
                content="参考上传图像的风格主题，生成符合文本描述的作品"
                placement="right"
              >
                <el-icon class="iconTip pl-5">
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
            </div>
            <div class="param-line">
              <div class="img-inline">
                <div class="img-list-box" v-if="params.image">
                  <!-- <div class="img-item flex-h" v-for="imgURL in imgList"> -->
                  <div class="img-item flex-h">
                    <div class="image-container">
                      <el-image :src="params.image" fit="cover" />
                      <div class="overlay ft-18">
                        <el-icon @click="removeUploadImage(imgURL)" class="mr-12 cursor"
                          ><Delete
                        /></el-icon>
                        <el-icon @click="uploadDialogVisivle = true" class="cursor"
                          ><UploadFilled
                        /></el-icon>
                      </div>
                    </div>
                    <div class="flex-1 p-15">
                      <div class="slider-demo-block flex-v flex-center">
                        <span class="demonstration"
                          ><p>
                            参考强度<span class="ft-12 t-gray">（数值越大参考强度越大）</span>
                          </p></span
                        >
                        <el-slider
                          v-model="params.imageFidelity"
                          :step="0.25"
                          :max="1"
                          :marks="marks"
                          style="
                            --el-slider-button-size: 14px;
                            --el-slider-main-bg-color: var(--input-radio-color);
                          "
                        />
                      </div>
                    </div>
                    <!-- <el-button
                      type="danger"
                      :icon="Delete"
                      @click="removeUploadImage(imgURL)"
                      circle
                    /> -->
                  </div>
                </div>
                <el-upload
                  v-else
                  class="img-uploader"
                  ref="upload"
                  :auto-upload="true"
                  :show-file-list="false"
                  :http-request="uploadImg"
                  accept=".png,.jpg,.jpeg,.bmp"
                  drag
                  style="--el-color-primary: #262238"
                  :limit="1"
                >
                  <!-- <el-icon class="uploader-icon">
                    <Plus />
                  </el-icon> -->
                  <div class="el-upload__text flex-h flex-center">
                    <!-- <el-icon class="mr-5"> -->
                    <i class="iconfont icon-upload liner-text mr-5">
                      <UploadFilled />
                    </i>
                    <!-- </el-icon> -->
                    <span class="ft-12 liner-text">点击/拖拽</span>
                  </div>
                  <template #tip>
                    <div class="el-upload__tip pb-10">
                      提示：支持 JPG / PNG 格式，文件大小不超过10MB，尺寸不小于300PX
                    </div>
                  </template>
                </el-upload>
              </div>
            </div>

            <div class="p-10">
              <div class="pb-15 flex-h flex-vh-center">
                <span>参数设置：</span>
              </div>
              <span class="picScale ft-12">图片比例：</span>
              <!-- <el-tooltip
                effect="light"
                content="生成图片的尺寸比例"
                placement="right"
              >
                <el-icon class="iconTip">
                  <InfoFilled />
                </el-icon>
              </el-tooltip> -->
            </div>

            <div class="param-line pt">
              <el-row :gutter="10">
                <template v-for="item in rates" :key="item.value">
                  <el-col :span="6" v-if="!item?.isShow || item?.isShow == params.platform">
                    <div
                      class="flex-col items-center"
                      :class="
                        item.value === params.aspectRatio ? 'grid-content active' : 'grid-content'
                      "
                      @click="changeRate(item)"
                    >
                      <!--                    <div :class="'shape ' + item.css"></div>-->
                      <el-image class="icon" :src="item.img" fit="contain"></el-image>
                      <div class="text">{{ item.text }}</div>
                    </div>
                  </el-col>
                </template>
              </el-row>
            </div>

            <div class="param-line pt">
              <span class="picScale ft-12">生成数量：</span>
              <el-popover
                placement="right"
                :width="200"
                trigger="hover"
                content="整活M只支持生成一张图片"
              >
                <template #reference>
                  <el-icon class="iconTip">
                    <InfoFilled />
                  </el-icon>
                </template>
              </el-popover>
              <!-- <el-tooltip
                effect="light"
                content="生成图片的尺寸比例"
                placement="right"
              >
                <el-icon class="iconTip">
                  <InfoFilled />
                </el-icon>
              </el-tooltip> -->
            </div>
            <div class="param-line pt ml-20 mr-20">
              <el-slider
                :disabled="params.platform === 'Jimeng'"
                v-model.number="params.n"
                :max="4"
                :min="1"
                :step="1"
                style="--el-slider-button-size: 14px"
              />
            </div>

            <div class="param-line">
              <!-- <el-row class="text-info">
                <el-tag
                  >每次绘图消耗{{ mjPower }}算力，U/V 操作消耗{{
                    mjActionPower
                  }}算力</el-tag
                >
                <el-tag type="success">当前可用算力：{{ power }}</el-tag>
              </el-row> -->

              <div class="submit-btn over-h posr">
                <el-tooltip :visible="tooltipVisivle && !params.prompt">
                  <template #content>
                    <span> 请输入创意描述</span>
                  </template>
                  <el-button
                    @mouseenter="tooltipVisivle = true"
                    @mouseleave="tooltipVisivle = false"
                    v-loading="isGen"
                    class="liner-btn-opacity liner-btn"
                    @click="generate"
                    :disabled="!!runningJobs.length || !params.prompt"
                    round
                    >开始创作</el-button
                  >
                </el-tooltip>
              </div>
            </div>
          </el-form>
        </div>
      </div>
      <div class="flex-1 flex-v flex-center middle-box">
        <!-- <task-list v-if="runningJobs.length" :list="runningJobs" /> -->
        <ImgGallery
          v-if="imgGallery && 'picUrl' in imgGallery"
          :raw="imgGallery"
          :list="[imgGallery]"
        />
        <Empty v-else image="/images/goose.gif" description="只要有绘画，就能勾勒出希望的轮廓。" />
        <!-- :image="require('@/assets/img/login-bg.jpg')" -->
      </div>
      <div class="task-list-box">
        <div class="task-list-inner h100">
          <div class="job-list-box h100 flex-v">
            <h2 class="ml-20 ft-16">历史</h2>
            <div
              class="finish-job-list waterfall-box flex-1 pr-10"
              v-infinite-scroll="getImageList"
              :style="{ height: `${listBoxHeight}px` }"
              :infinite-scroll-distance="20"
              :infinite-scroll-disabled="isOver"
              :infinite-scroll-immediate="false"
              v-if="imageList.length > 0"
            >
              <!-- :colWidth="colWidth" -->
              <div
                v-for="(item, index) in imageList"
                class="job-item"
                @click="historyClickHandle(item, index)"
              >
                <template v-if="item.status !== AiImageStatusEnum.SUCCESS">
                  <div
                    :style="{
                      height: '245px',
                    }"
                  >
                    <GenLoading :status="item.status" :errorMessage="item.errorMessage" />
                  </div>
                </template>
                <el-image
                  v-else
                  :class="{ active: item?.id == imageList[current]?.id }"
                  :style="{
                    height: item.status !== AiImageStatusEnum.SUCCESS && '245px',
                  }"
                  :src="item.picUrl"
                  @click="previewImg(item)"
                  fit="cover"
                  loading="lazy"
                >
                  <!-- :preview-src-list="imageList.img.split()" -->
                  <template #placeholder>
                    <div class="image-slot">
                      <GenLoading :status="item.status" :errorMessage="item.errorMessage" />
                    </div>
                  </template>
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="history-title flex-h flex-between mb-5">
                  <h4
                    class="text-ellipsis"
                    :style="{
                      color: item.status !== AiImageStatusEnum.SUCCESS ? '#000' : '#fff',
                    }"
                    :title="item.prompt"
                  >
                    {{ item.prompt }}
                  </h4>
                  <!-- <h4>{{ item.n }}张</h4> -->
                </div>
                <div class="gallery-icon" v-if="item.status == AiImageStatusEnum.SUCCESS">
                  <el-icon @click.stop="removeImage(item)"><Delete /></el-icon>
                </div>
              </div>
              <!-- <div class="no-more-data" v-if="isOver">
                <span>没有更多数据了</span>
                <i class="iconfont icon-face"></i>
              </div> -->
            </div>
            <el-empty :image-size="100" v-else />
            <!-- end finish job list-->
          </div>
        </div>
        <back-top :right="30" :bottom="30" bg-color="#0f7a71" />
      </div>
      <!-- end task list box -->
    </div>

    <!-- <el-image-viewer
      @close="
        () => {
          previewURL = '';
        }
      "
      v-if="previewURL !== ''"
      :url-list="[previewURL]"
    /> -->
    <el-dialog
      v-model="uploadDialogVisivle"
      title="上传图片"
      width="500"
      v-if="uploadDialogVisivle"
    >
      <el-upload
        class="img-uploader"
        ref="dialogupload"
        :auto-upload="true"
        :show-file-list="false"
        :http-request="uploadImg"
        accept=".png,.jpg,.jpeg,.bmp"
        drag
      >
        <!-- <el-icon class="uploader-icon">
                    <Plus />
                  </el-icon> -->
        <div class="el-upload__text flex-h flex-center">
          <el-icon class="t-blue mr-5">
            <UploadFilled />
          </el-icon>
          <span class="t-blue">点击/拖拽</span>
        </div>
        <template #tip>
          <div class="el-upload__tip t-blue">
            提示：支持 JPG / PNG 格式，文件大小不超过10MB，尺寸不小于300PX
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, reactive, useTemplateRef } from "vue";
import {
  ChromeFilled,
  Delete,
  DocumentCopy,
  InfoFilled,
  Upload,
  Picture,
  Plus,
  UploadFilled,
} from "@element-plus/icons-vue";
import Compressor from "compressorjs";
import { httpGet, httpPost } from "@/utils/http";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import Clipboard from "clipboard";
import { useRouter } from "vue-router";
import { getSessionId } from "@/store/session";
import { copyObj, removeArrayItem } from "@/utils/libs";
import { useSharedStore } from "@/store/sharedata";
import TaskList from "@/components/TaskList.vue";
import ImgGallery from "@/components/ImgGallery.vue";
import BackTop from "@/components/BackTop.vue";
import { compact } from "lodash-es";
import Empty from "@/components/Empty.vue";
import { ImageApi } from "@/api/ai/image";
import { updateFile } from "@/api/file";
import { AiImageStatusEnum } from "@/utils/ai/constants";
import GenLoading from "@/components/GenLoading.vue";
import { removeFindIndex } from "@/utils/ai";
const tags = ref([
  { label: "火山", value: "火山" },
  { label: "吃饺子", value: "吃饺子" },
  { label: "狮子", value: "狮子" },
  { label: "骆驼", value: "骆驼" },
  { label: "柯基", value: "柯基" },
  { label: "油画少女", value: "油画少女" },
  { label: "太空战机", value: "太空战机" },
  { label: "金字塔", value: "金字塔" },
  { label: "白猫", value: "白猫" },
  { label: "赛博城市", value: "赛博城市" },
  { label: "熊猫", value: "熊猫" },
]);
// console.log("import.meta :>> ", import.meta);
const listBoxHeight = ref(0);
const paramBoxHeight = ref(0);
const loading = ref(true);
const colWidth = ref(220);
const previewURL = ref("");
const store = useSharedStore();
const tooltipVisivle = ref(false);
const isMounted = ref(false);
const uploadDialogVisivle = ref(false);
const resizeElement = function () {
  listBoxHeight.value = window.innerHeight - 45;
  paramBoxHeight.value = window.innerHeight - 160;
};
resizeElement();
window.onresize = () => {
  resizeElement();
};

const rates = [
  { css: "square", value: "21:9", text: "21:9", img: "/images/mj/rate_21_9.png", isShow: "Jimeng" },
  {
    css: "size16-9",
    value: "16:9",
    text: "16:9",
    img: "/images/mj/rate_16_9.png",
  },
  { css: "size4-3", value: "4:3", text: "4:3", img: "/images/mj/rate_4_3.png" },
  { css: "size3-2", value: "3:2", text: "3:2", img: "/images/mj/rate_4_3.png" },
  { css: "square", value: "1:1", text: "1:1", img: "/images/mj/rate_1_1.png" },
  // { css: "size1-2", value: "1:2", text: "1:2", img: "/images/mj/rate_1_2.png" },
  // { css: "size2-1", value: "2:1", text: "2:1", img: "/images/mj/rate_2_1.png" },
  { css: "size2-3", value: "2:3", text: "2:3", img: "/images/mj/rate_3_4.png" },
  { css: "size3-4", value: "3:4", text: "3:4", img: "/images/mj/rate_3_4.png" },
  {
    css: "size9-16",
    value: "9:16",
    text: "9:16",
    img: "/images/mj/rate_9_16.png",
  },
];
const models = [
  { text: "写实模式MJ-6.1", value: " --v 6.1", img: "/images/mj/mj-v6.png" },
  { text: "优质模式MJ-6.0", value: " --v 6", img: "/images/mj/mj-v5.2.png" },
  { text: "优质模式MJ-5.2", value: " --v 5.2", img: "/images/mj/mj-v5.1.jpg" },
  { text: "虚幻模式MJ-5.1", value: " --v 5.1", img: "/images/mj/mj-v5.jpg" },
  { text: "真实模式MJ-4", value: " --v 4", img: "/images/mj/mj-v4.jpg" },
  { text: "动漫风-niji4", value: " --niji 4", img: "/images/mj/nj4.jpg" },
  { text: "动漫风-niji5", value: " --niji 5", img: "/images/mj/mj-niji.png" },
  {
    text: "动漫风-niji5 可爱",
    value: " --niji 5 --style cute",
    img: "/images/mj/nj1.jpg",
  },
  {
    text: "动漫风-niji5 风景",
    value: " --niji 5 --style scenic",
    img: "/images/mj/nj2.jpg",
  },
  { text: "动漫风-niji6", value: " --niji 6", img: "/images/mj/nj3.jpg" },
];

const router = useRouter();
const marks = reactive({
  0: "弱",
  0.25: "较弱",
  0.5: "中",
  0.75: "较强",
  1: "强",
});
const platformOption = [
  {
    label: "整活M",
    value: "Jimeng",
  },
  {
    label: "整活K",
    value: "Keling",
  },
];
const modelVersionOption = ref([]);
// 当前选中的模型版本obj
const curModelSelected = computed(() => {
  return modelVersionOption.value.find((item) => item.model === params.value.model);
});
// 当前选中模型是否支持 图生图
const curModeli2iFlag = computed(() => {
  return curModelSelected.value?.i2iFlag;
});
// 定义不同版本的尺寸映射
const dimensionMappings = {
  "1K": {
    "1:1": { width: 1328, height: 1328 },
    "4:3": { width: 1472, height: 1104 },
    "3:4": { width: 1104, height: 1472 },
    "3:2": { width: 1584, height: 1056 },
    "2:3": { width: 1056, height: 1584 },
    "16:9": { width: 1664, height: 936 },
    "9:16": { width: 936, height: 1664 },
    "21:9": { width: 2016, height: 864 },
  },
  "2K": {
    "1:1": { width: 2048, height: 2048 },
    "4:3": { width: 2304, height: 1728 },
    "3:4": { width: 1728, height: 2304 },
    "3:2": { width: 2496, height: 1664 },
    "2:3": { width: 1664, height: 2496 },
    "16:9": { width: 2560, height: 1440 },
    "9:16": { width: 1440, height: 2560 },
    "21:9": { width: 3024, height: 1296 },
  },
};

/**
 * 根据比例和版本获取宽高尺寸
 * @param {string} ratio 比例值，如 "16:9"
 * @param {'1K'|'2K'} version 版本
 * @returns {{width: number, height: number}}
 */
function getDimensions(ratio, version = "1K") {
  console.log("version :>> ", version);
  if (typeof version == "boolean") {
    version = version ? "2K" : "1K";
  }
  return dimensionMappings[version][ratio] || { width: 512, height: 512 };
}
// 设置参数的宽和高
const setParamsWH = () => {
  Object.assign(
    params.value,
    getDimensions(params.value.aspectRatio, curModelSelected.value?.highFlag),
    {}
  );
};
const initParams = {
  platform: platformOption[0].value,
  model: "",
  type: "text2image",
  image: "",
  img_arr: [],
  aspectRatio: "1:1",
  model: models[0].value,
  // 参考强度
  imageFidelity: 0.75,
  chaos: 0,
  stylize: 0,
  seed: 0,
  raw: false,
  iw: 0,
  prompt: router.currentRoute.value.params["prompt"] ?? "",
  neg_prompt: "",
  tile: false,
  quality: 0,
  cref: "",
  sref: "",
  cw: 0,
  // 生成图片数量
  n: 1,
  width: "",
  height: "",
};
const params = ref(copyObj(initParams));
const selectTag = (tag) => {
  if (params.value.prompt.length + tag.value.length >= 119) {
    return;
  }
  params.value.prompt = compact([...params.value.prompt.split(","), tag.value]).join(",");
};
// const imgList = ref(["http://localhost:8888/images/vip.png"]);
const imgList = ref([]);

const activeName = ref("txt2img");

const runningJobs = ref([]);
// const runningJobs = ref([{a:1},{a:1},{a:1},{a:1}]);
const imageList = ref([]);

const socket = ref(null);
const power = ref(0);
const userId = ref(0);
const isLogin = ref(false);

// 图片轮询相关的参数（正在生成中的）
const inProgressImageMap = ref({}); // 监听的 image 映射，一般是生成中（需要轮询），key 为 image 编号，value 为 image
const inProgressTimer = ref(); // 生成中的 image 定时器，轮询生成进展
const heartbeatHandle = ref(null);
const imgGallery = ref({});
const current = ref();
const historyClickHandle = (item, i) => {
  if (!item.picUrl) {
    return;
  }
  item.options.imageFidelity = +item.options.imageFidelity;
  console.log("item :>> ", item);
  params.value = Object.assign({}, params.value, item.options);
  current.value = i;
  imgGallery.value = item;
};
const clipboard = ref(null);
onMounted(() => {
  initData();
  isMounted.value = true;
  clipboard.value = new Clipboard(".copy-prompt-mj");
  clipboard.value.on("success", () => {
    ElMessage.success("复制成功！");
  });

  clipboard.value.on("error", () => {
    ElMessage.error("复制失败！");
  });
});

onUnmounted(() => {
  clearInterval(inProgressTimer.value);
  clipboard.value.destroy();
  if (socket.value !== null) {
    socket.value.close();
    socket.value = null;
  }
});

// 初始化数据
const initData = async () => {
  await getImageList();
  await getImageModelList();
  // 自动刷新 image 列表
  inProgressTimer.value = setInterval(async () => {
    await refreshWatchImages();
  }, 1000 * 3);
};
// 获取模型版本
const getImageModelList = async (platform) => {
  const data = await ImageApi.getImageModelList({
    platform: "Jimeng",
  });
  modelVersionOption.value = [...data];
  checkModelToi2iFlag(data);
};
// 重置模型到 可图生图版本的第一个 当前只是即梦 keling没模型
const checkModelToi2iFlag = (modelOption) => {
  // 当前是可以传图版本 return
  if (curModeli2iFlag.value) {
    return;
  }
  if (params.value.platform != "Jimeng") {
    return;
  }
  // 支持选图的第一个模型
  const i2iFlagObj = modelOption.find((d) => d.i2iFlag);
  console.log(
    "%c更改模型版本%o",
    "color: white; background-color: #61ee98; padding: 2px 5px; border-radius: 2px",
    i2iFlagObj.model
  );
  params.value.model = i2iFlagObj.model;
};
const mjPower = ref(1);
const mjActionPower = ref(1);
const pageTotal = ref();
/** 获得 image 图片列表 */
const getImageList = async () => {
  console.log("加载更多");
  if (queryParams.pageNo == 0) {
    isOver.value = false;
  }
  if (isOver.value) {
    return;
  }
  loading.value = true;
  queryParams.pageNo += 1;
  try {
    // 1. 加载图片列表
    // imageListLoadingInstance.value = ElLoading.service({
    //   target: imageListRef.value,
    //   text: "加载中...",
    // });
    const { list, total } = await ImageApi.getImagePageMy(queryParams);
    if (list.length < queryParams.pageSize) {
      isOver.value = true;
    }
    if (queryParams.pageNo === 1) {
      imageList.value = list;
    } else {
      imageList.value = imageList.value.concat(list);
    }
    pageTotal.value = total;

    // 2. 计算需要轮询的图片
    const newWatImages = {};
    imageList.value.forEach((item) => {
      if (item.status === AiImageStatusEnum.IN_PROGRESS) {
        newWatImages[item.id] = item;
      }
    });
    inProgressImageMap.value = newWatImages;
  } finally {
    // 关闭正在“加载中”的 Loading
    // if (imageListLoadingInstance.value) {
    //   imageListLoadingInstance.value.close();
    //   imageListLoadingInstance.value = null;
    // }
  }
};
const isGen = ref(true);
/** 轮询生成中的 image 列表 */
const refreshWatchImages = async () => {
  isGen.value = true;
  const imageIds = Object.keys(inProgressImageMap.value).map(Number);
  if (imageIds.length == 0) {
    isGen.value = false;
    console.log(
      "%c当前无任务",
      "color: white; background-color: #61ee98; padding: 2px 5px; border-radius: 2px"
    );
    return;
  }
  const list = await ImageApi.getImageListMyByIds(imageIds);

  const newWatchImages = {};
  list.forEach((image) => {
    if (image.status === AiImageStatusEnum.IN_PROGRESS) {
      newWatchImages[image.id] = image;
    } else {
      const index = imageList.value.findIndex((oldImage) => image.id === oldImage.id);
      if (index >= 0) {
        // 更新 imageList
        imageList.value[index] = image;
      }
    }
  });
  let isOver = list.every(
    (d) => d.status == AiImageStatusEnum.SUCCESS || d.status == AiImageStatusEnum.FAIL
  );
  console.log("isOver :>> ", isOver);
  // hack  !imgGallery.value删除索引下的图片 imgGallery.value 为null了就
  if (isOver && (!imgGallery.value || !Object.keys(imgGallery.value).length)) {
    imgGallery.value = imageList.value[0];
    current.value = 0;
  }
  inProgressImageMap.value = newWatchImages;
};

const page = ref(0);
const pageSize = ref(8);
// 图片分页相关的参数
const queryParams = reactive({
  pageNo: 0,
  pageSize: 10,
});
const isOver = ref(false);
// 模型切换 一系列操作
const platformChange = (val) => {
  // 可灵不支持21:9
  if (val == "Keling" && params.value.aspectRatio == "21:9") {
    params.value.aspectRatio = "1:1";
  }
  // 即梦只支持生成一张
  if (val == "Jimeng" && params.value.num > 1) {
    params.value.n = 1;
  }
};
// 切换图片比例
const changeRate = (item) => {
  params.value.aspectRatio = item.value;
};
// 切换模型
const changeModel = (item) => {
  params.value.model = item.value;
};

const imgKey = ref("");
const beforeUpload = (key) => {
  imgKey.value = key;
};

// 图片上传
const uploadImg = async (file) => {
  // if (!isLogin.value) {
  //   store.setShowLoginDialog(true);
  //   return;
  // }

  // 压缩图片并上传
  new Compressor(file.file, {
    quality: 0.6,
    success(result) {
      const formData = new FormData();
      formData.append("file", result, result.name);
      // 执行上传操作
      updateFile(formData)
        .then((res) => {
          if (imgKey.value === "") {
            // 暂时单图
            imgList.value.push(res.data);
            params.value.image = res.data;
          } else {
            // 单张图片上传
            params.value[imgKey.value] = res.data;
            imgKey.value = "";
          }
          ElMessage.success("上传成功");
          if (uploadDialogVisivle.value) {
            uploadDialogVisivle.value = false;
            imgList.value = imgList.value.slice(-1);
          }
          checkModelToi2iFlag([...modelVersionOption.value]);
          // removeUploadFiles()
        })
        .catch((e) => {
          ElMessage.error("上传失败:" + e.message);
        });
    },
    error(err) {
      console.log(err.message);
    },
  });
};

// 创建绘图任务
const promptRef = ref(null);
const generate = async () => {
  if (runningJobs.length) {
    ElMessage.error("有任务正在执行，请等待任务完成！");
    return;
  }
  // if (!isLogin.value) {
  //   store.setShowLoginDialog(true);
  //   return;
  // }
  if (params.value.prompt === "" && params.value.type === "image") {
    promptRef.value.focus();
    return ElMessage.error("请输入绘画提示词！");
  }
  if (params.value.model.indexOf("niji") !== -1 && params.value.raw) {
    return ElMessage.error("动漫模型不允许启用原始模式");
  }
  if (imgList.value.length !== 2 && params.value.type === "swapFace") {
    return ElMessage.error("换脸操作需要上传两张图片");
  }
  params.value.session_id = getSessionId();
  if (params.value.image) {
    params.value.type = "image2image";
  }
  params.value.img_arr = imgList.value;
  isGen.value = true;
  setParamsWH();
  await ImageApi.drawImage(params.value);
  if (current.value != null) {
    current.value += params.value.n;
  }
  queryParams.pageNo = 0;
  await getImageList();
};

// 图片放大任务
const upscale = (index, item) => {
  send("/api/keling/upscale", index, item);
};

// 图片变换任务
const variation = (index, item) => {
  send("/api/keling/variation", index, item);
};

const send = (url, index, item) => {
  httpPost(url, {
    index: index,
    channel_id: item.channel_id,
    message_id: item.message_id,
    message_hash: item.hash,
    session_id: getSessionId(),
    prompt: item.prompt,
  })
    .then(() => {
      ElMessage.success("任务推送成功，请耐心等待任务执行...");
      power.value -= mjActionPower.value;
    })
    .catch((e) => {
      ElMessage.error("任务推送失败：" + e.message);
    });
};

const removeImage = (item) => {
  ElMessageBox.confirm("此操作将会删除任务和图片，继续操作吗?", "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ImageApi.deleteImageMy(item.id)
        .then(async () => {
          removeFindIndex(imageList, item.id, imgGallery, current);
          ElMessage.success("任务删除成功");
          queryParams.pageNo = 0;
          await getImageList();
        })
        .catch((e) => {
          // ElMessage.error("任务删除失败：" + e.message);
        });
    })
    .catch(() => {});
};

const previewImg = (item) => {
  previewURL.value = item.img_url;
};

// 切换菜单
const tabChange = (tab) => {
  if (tab === "txt2img" || tab === "img2img" || tab === "cref") {
    params.value.type = "image";
  } else {
    params.value.type = tab;
  }
};

// 删除已上传图片
const removeUploadImage = (url) => {
  imgList.value = removeArrayItem(imgList.value, url);
  params.value.image = "";
};
const upload = useTemplateRef("upload");
const removeUploadFiles = (params) => {
  console.log("删除clearFiles");
  upload.value.clearFiles();
};
</script>

<style lang="stylus" scoped>
@import "../assets/css/image-mj.styl"
@import "../assets/css/custom-scroll.styl"
</style>
